#!/bin/sh


#    Copyright (c) 1996-2004 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Description:
#      Install script that initializes a platform
#


# Set the LD_LIBRARY_PATH for the interdependency 
export LD_LIBRARY_PATH="/lib:/usr/lib"

usage() {
    program=`basename $0`

    echo "Usage: $program <platform> <TEST | EXTENDED> package"
    echo "  platform      <Optional> hardware must be this platform."
    echo "  TEST          Perform read/write testing of compact flash memory."
    echo "  EXTENDED      Perform extended testing of compact flash memory."
    echo "  package       Package to install."

    echo ""
    echo "Platforms for this product are:"
    cat platform_names | grep $PLATFORM | cut -d":" -f2- | xargs
    echo ""
    echo "Platform \"$PLATFORM\" packages are:"
    ls ./$PLATFORM/*.plist 2>/dev/null | cut -d"/" -f3 | cut -d "." -f1
    echo ""
    exit 1
}

exit_out()
{
    if [ $error = TRUE ]
    then
	echo "SCRIPT: install FAILED with $warn_count warnings."
	exit 1
    else
	if [ $warn_count -gt 0 ]
	then
	    echo "SCRIPT: install PASSED with $warn_count warnings."
	else
	    echo "SCRIPT: install PASSED."
	fi
	exit 0
    fi
}

#
# do_command <warn/error> <command...>
#
do_command()
{
    warn=$1
    shift
    $*
    if [ $? -ne 0 ]
    then
	if [ $warn = TRUE ]
	then
	    echo "SCRIPT: Warning - failed $0 $*"
	    warn_count=`expr $warn_count + 1`
	    return 1
	else
	    echo "SCRIPT: ERROR - failed $0 $*"
	    continue=FALSE
	    error=TRUE
	    exit_out
	fi
    fi
    return 0
}
#
# install-rpms <plist> <root>
#
installrpms()
{
    LIST=$PLATFORM/$1

    if [ ! -f $LIST ] || [ ! -r $LIST ]; then
	echo "SCRIPT: Cannot open/read package list to install."
	exit 1
    fi

    if [ ! -z $2 ]; then
	ROOT=$2
    else
        ROOT=/
    fi

    RPM="rpm --root $ROOT"

    echo "SCRIPT: Installing RPMs from $LIST rooted at $ROOT..."

    if [ ! -d ${ROOT}/var/lib/rpm ]; then
        echo "SCRIPT: Initializing RPM database..."
	do_command FALSE mkdir -p ${ROOT}/var/lib/rpm
	do_command FALSE rpm --root $ROOT --initdb
    fi

    for package in `cat $LIST | dd skip=18 bs=16 2> /dev/null | grep -v '#' | xargs`;
    do
	#
	# Only install the package if it hasn't already been installed
	# 
#	if ! $RPM -q `echo $package | sed -e "s,\([[:graph:]]\+-[.[:alnum:]]\+-[[:alnum:]]\+\)\.\([[:alnum:]]\+\)\.\(rpm\),\1,g"` > /dev/null 2>&1; then
	    do_command TRUE $RPM --force --nodeps -ivUh $package
	    if [ $? -ne 0 ]
	    then
		do_command FALSE $RPM --force --nodeps -ivUh $package
	    fi
#	fi
    done
}
#
# test_for_package <candidate>
#
test_for_package()
{
    abc=`echo $1 | tr -s '[:upper:]' '[:lower:]'`

    #
    # See if first parameter was a PACKAGE
    #
    if [ -f ./$PLATFORM/$abc.plist ]
    then
	echo $abc
    else
	echo FALSE
    fi
}
#
# test_for_test <candidate>
#
test_for_test()
{
    if [ "$1" = "TEST" ]
    then
	echo 1
    else
	if [ "$1" = "EXTENDED" ]
	then
	    echo 2
	else
	    echo FALSE
	fi
    fi
}

#
# parse the command line arguments
#
parse_arguments()
{
    # check explicitly for package and test parameters, and assume 
    # anything else is the plaftorm validation
    #
    while [ $# -gt 0 ]
    do
	result=`test_for_package $1`
	if [ "$result" = "FALSE" ]
	then
	    result=`test_for_test $1`
	    if [ "$result" = "FALSE" ]
	    then
		#
		# Look up the name in the list of known names for the platform ID
		#
		TARGET_PLATFORM=`echo $1 | tr "A-Z" "a-z"`
		target=`grep $PLATFORM platform_names`
		if [ "$target" == "" ]
		then
		    echo "SCRIPT: Unknown Platform found $PLATFORM"
		    usage
		fi
		if [ "`echo $target | grep $TARGET_PLATFORM`" = "" ]
		then
		    echo "SCRIPT: Actual platform ($PLATFORM) does not match specified platform $1."
		    echo "SCRIPT: ERROR - failed $0 $*"
		    continue=FALSE
		    error=TRUE
		    exit_out
		fi

		if [ -z $PLATFORM ]
		then
		    if [ ! -d ./$TARGET_PLATFORM ]
		    then
			echo "SCRIPT: Unknown Platform specified $TARGET_PLATFORM"
			usage
		    fi
		    PLATFORM=$TARGET_PLATFORM
		    case $PLATFORM in
			"SWBD10" ) REVISION=0;;
			"SWBD12" ) REVISION=3;;
			"SWBD21" ) REVISION=0;;
			"SWBD23" ) REVISION=0;;
			"SWBD22" ) REVISION=0;;
			"SWBD26" ) REVISION=0;;
			"SWBD27" ) REVISION=0;;
			"SWBD28" ) REVISION=0;;
			"SWBD29" ) REVISION=0;;
			"SWBD30" ) REVISION=0;;
			"SWBD31" ) REVISION=0;;
			"SWBD32" ) REVISION=0;;
			"SWBD33" ) REVISION=0;;
			*) REVISION=0;;
		    esac
		fi
	    else
		do_test=$result
	    fi
	else
	    PACKAGE=$result
	fi
	shift
    done
#######################
# Check the parameters
#
if [ ! -f ./$PLATFORM/$PACKAGE.plist ]
then
    printf "SCRIPT: Incorrect package %s\n" $PACKAGE
    usage
fi
}

#------------------------------
# BEGIN MAIN PART OF THE SCRIPT
# BEGIN MAIN PART OF THE SCRIPT
#------------------------------

if [ -z `pwd | grep load` ]
then
    echo "SCRIPT: ERROR install directory is not mounted on /load."
    exit 1
fi

for mnt in `mount | cut -d" " -f3 | grep "/mnt"`
do
    umount $mnt
done

FS='xfs'
FSOPTS='-f'
DEVICE='hda'
TMPMNT='/mnt'
do_test=NOTEST
warn_count=0
continue=TRUE
error=FALSE

echo "SCRIPT: Installing new NFS root packages..."
PACKAGE="no_package_defined"
node="platform"
major=`grep $node\$ /proc/devices | cut -d ' ' -f 1`
if [  $major ]; then
    rm -f /dev/$node
    mknod --mode=644 /dev/$node c $major 0
fi

if [ ! -f /bin/sin ]
then
     # NMB if we cannot determine the platform using /bin/sin
     # which means we are using older versions of install image
     # if so assume the platform is what we have been passed with
     # and it should be one of the subdirectories 
     # once we install the net.plist we should be able to
     # determine the right platform - using /bin/sin
     PLATFORM=`echo $1`

     # fixing up the links and directories for installation of net.plist
     if [ ! -d /fabos ]
     then
         mkdir /fabos
     fi
     if [ ! -d /fabos/lib ]
     then
         mkdir /fabos/lib
     fi
     if [ ! -f /lib/libdb.so ]
     then
         ln -s /lib/libdb.so.3 /lib/libdb.so
     fi
     if [ ! -d /boot ]
     then
         mkdir /boot
     fi
     cp ./$PLATFORM/System.map /boot/System.map
     chmod 777 /boot/System.map
     installrpms net.plist
fi

PLATFORM=`sin | \
		  /bin/grep Platform | \
		  /usr/bin/cut -d" " -f2 | \
		  /usr/bin/cut -d"," -f1`

REVISION=`sin | \
		  /bin/grep Platform | \
		  /usr/bin/cut -d" " -f4`


TARGET_PLATFORM=$PLATFORM
######################
# parse the arguments
#
parse_arguments $*
case "$PLATFORM" in
     "SWBD23" | "SWBD26" | "SWBD27" | "SWBD29" | "SWBD32" | "SWBD33" )
	FS=ext3
	;;
esac

##############################################
# Let's get down to it and install this thing
#
echo "SCRIPT: INSTALLING for platform: $PLATFORM revision: $REVISION package $PACKAGE"

echo "SCRIPT: Finding module dependencies..."

if [ ! -h /lib/modules/`uname -r` ]; then
	ln -sf default /lib/modules/`uname -r`
fi

do_command FALSE depmod -Aqe

if [ ! -d /proc/ide/ide0 ]
then
    echo "SCRIPT: Starting services..."

    do_command FALSE chkconfig pcmcia on
    do_command FALSE /etc/rc.d/init.d/pcmcia start
fi

max_count=30
echo -n "SCRIPT: Determining drive capacity (MAX $max_count sec)"

count=0
while [ ! -f /proc/ide/${DEVICE}/capacity -a $count -lt $max_count ]; do
	echo -n "."
	sleep 1
	count=`expr $count + 1`
done
echo ""
if [ $count -ge $max_count ]
then
    echo "SCRIPT: Failed to determine drive capacity. Perhaps pcmcia driver did not start correctly."
    error=TRUE
    exit_out
fi


echo "SCRIPT: Partitioning drive..."

BLOCKS=`cat /proc/ide/${DEVICE}/capacity`
((HALFMB = BLOCKS >> 12))
((ENDMB = 2 * HALFMB))

# Workaround until the page_alloc.c bug is fixed... -bk
if [ "$PLATFORM" = "SWBD24" ]; then
	((HALFMB = 128))
	((ENDMB = 256))
fi

do_command FALSE parted -s /dev/${DEVICE} mklabel msdos
do_command FALSE parted -s /dev/${DEVICE} mkpart primary $FS 0.000 $HALFMB.000
do_command FALSE parted -s /dev/${DEVICE} mkpart primary $FS $HALFMB.000 $ENDMB.000
do_command FALSE parted -s /dev/${DEVICE} print

for partition in 1 2; do
  if [ $continue = TRUE ]
  then
    #
    # if this is a Ulysses box, then program the backplane mac address
    #
    if [ ${partition} -eq 1 ]
    then
	if [ -f ./$PLATFORM/bpmac -a "$PLATFORM" != "SWBD21" ]
	then
	    echo "SCRIPT: Setting up Private Ethernet mac address"
	    do_command FALSE ./$PLATFORM/bpmac
	fi
    fi

    echo "SCRIPT: Creating $FS file system on /dev/${DEVICE}${partition}..."

    case "$PLATFORM" in
    	"SWBD23" | "SWBD26" | "SWBD27" | "SWBD29" | "SWBD32" | "SWBD33" )
		do_command FALSE mke2fs -g32768 -b4096 -j /dev/${DEVICE}${partition}
		do_command FALSE tune2fs -c 0 -i 0 /dev/${DEVICE}${partition}
		;;
	* )
    		do_command FALSE mkfs -t $FS $FSOPTS /dev/${DEVICE}${partition}
		;;
    esac

    if [ "$do_test" = NOTEST ]
    then
	echo "SCRIPT: Skipping the memory tests"
    else
	if [ "$do_test" = 1 ]
	then
	    echo "SCRIPT: Running the Read/Write memory tests"
	else
	    echo "SCRIPT: Running the EXTENDED memory tests"
	fi

	# use the platform specific sbin, default to 405 
	if [ -f ./$PLATFORM/sbin/blockcheck ]
	then
	    echo "SCRIPT: Running ./$PLATFORM/sbin/blockcheck"
	    ./$PLATFORM/sbin/blockcheck -t $do_test -v /dev/${DEVICE}${partition}
	else
	    echo "SCRIPT: Running ./sbin/blockcheck"
	    ./sbin/blockcheck -t $do_test -v /dev/${DEVICE}${partition}
	fi
	echo "SCRIPT: Recreating $FS file system on /dev/${DEVICE}${partition}..."

	case "$PLATFORM" in
    		"SWBD23" | "SWBD26" | "SWBD27" | "SWBD29" | "SWBD32" | "SWBD33" )
			do_command FALSE mke2fs -g32768 -b4096 -j /dev/${DEVICE}${partition}
			do_command FALSE tune2fs -c 0 -i 0 /dev/${DEVICE}${partition}
			;;
		* )
    			do_command FALSE mkfs -t $FS $FSOPTS /dev/${DEVICE}${partition}
			;;
	esac
    fi

    echo "SCRIPT: Mounting primary file system on ${TMPMNT}..."

    do_command FALSE mount -t $FS /dev/${DEVICE}${partition} ${TMPMNT}

    #
    # Install soft-link for modules
    #
    do_command FALSE mkdir /mnt/lib
    do_command FALSE mkdir /mnt/lib/modules
    do_command FALSE ln -sf default /mnt/lib/modules/`uname -r`

    #
    # Make sure groups are installed.
    #
    do_command FALSE mkdir /mnt/etc
    do_command FALSE cat ./$PLATFORM/group > /mnt/etc/group
#    do_command FALSE cat > /mnt/etc/group << EOF
#root::0:root
#bin::1:root,bin,daemon
#daemon::2:root,bin,daemon
#sys::3:root,bin,adm
#EOF
    #
    # Create fabos/lib
    #
    do_command FALSE mkdir /mnt/fabos
    do_command FALSE mkdir /mnt/fabos/lib

    #
    # Fix termcap / readline chicken and egg problem
    #
    do_command FALSE cp /lib/libtermcap.so.1 /mnt/lib

    #
    # Create device nodes and symlinks that can only be created
    # at runtime.
    # First the mtd symlinks
    #
    do_command FALSE mkdir /mnt/dev
    while read var1 var2 var3 var4 var5
    do
	    # We do this check to get rid of initial comment string
	    if [ "$var1" == "dev:" ];
	    then
		    continue;
	    fi

	    # What if its an empty line
	    if [ "x$var1" == "x" ];
	    then
		    continue;
	    fi
	    # Strip devname off the ":"
	    devname=${var1%:}

	    # If var4 contains a ":" tmpvar will be NULL
	    tmpvar=${var4##*:*}

	    # Check if tmpvar is NULL
	    if [ "x$tmpvar" == "x" ]; then
		    # Build dev_alias with removing initial '"'
		    dev_alias=${var4#\"};
		    # dev_alias does not need the ending:
		    dev_alias=${dev_alias%:};

		    # Do the actual linking for the dev_alias->devname
		    ln -s -f /dev/$devname /mnt/dev/$dev_alias
	    fi
    done </proc/mtd

    # Next the platform device
    node="platform"
    major=`grep $node\$ /proc/devices | cut -d ' ' -f 1`
    if [  $major ]; then
	rm -f /mnt/dev/$node
	mknod --mode=644 /mnt/dev/$node c $major 0
    fi


    installrpms $PACKAGE.plist ${TMPMNT}

    ####################################
    # Run platform specific install if required
    if [ -f $PLATFORM/install ]
    then
	echo "SCRIPT: Running $PLATFORM/install"
	$PLATFORM/install $PLATFORM $PACKAGE
    fi

    ####################################
    # load the manufacturing additions
    # After the normal rpm's and PLATFORM specific process has been completed,
    # then install the manufacturing overlays it they exist. We must be 
    # specific, and only take this action if the PACKAGE is factory or 
    # development. DO NOT do this for the release SW.

    if [ "$PACKAGE" = factory -o "$PACKAGE" = development -o "$PACKAGE" = foslight ]
    then
	for fil in `ls ./$PLATFORM/Mfgtests/*/* 2>/dev/null`
	do
	    script=`echo $fil | cut -d"/" -f4-`
	    echo "SCRIPT: Loading $script"
	    do_command FALSE cp $fil /mnt/fabos/$script
	    do_command FALSE chmod 0755 /mnt/fabos/$script
	    do_command FALSE chgrp factory /mnt/fabos/$script
	    # if there are additions for manufacturing, then the rpm -V that 
	    # happens during boot (controlled by the NoSysTest boot 
	    # environment variable) will most likely fail, so turn of the
  	    # the rpm -V (only once though).
	done
    fi

    echo "SCRIPT: Updating the file system table..."

    cat > ${TMPMNT}/etc/fstab << EOF
/dev/root	/		$FS	rw,noatime	0 0
none		/proc		proc	defaults	0 0
none		/dev/pts	devpts	mode=620	0 0
EOF

    echo "SCRIPT: Fixing up pdm wrong directory for rcp"
    do_command FALSE ln -sf ../usr/bin/rcp /mnt/bin/rcp

    echo "SCRIPT: Fixing up /etc/modules.conf..."

    do_command FALSE cat > /mnt/etc/modules.conf << EOF
keep
path=/fabos/modules
alias eth1 eepro100
EOF

    echo "SCRIPT: Fixing fabos/sbin/sname"
    if [ ! -x /mnt/fabos/sbin/sname ] ; then
          ln -sf ../bin/sname /mnt/fabos/sbin/sname
    fi

    echo "SCRIPT: Creating release file"
    # use the platform specific sbin, default to 405 
    if [ -f ./$PLATFORM/sbin/create_release_file ]
    then
	echo "SCRIPT: Running ./$PLATFORM/sbin/create_release_file"
	./$PLATFORM/sbin/create_release_file -p $PLATFORM -l $PACKAGE
    else
	echo "SCRIPT: Running ./sbin/create_release_file"
	./sbin/create_release_file -p $PLATFORM -l $PACKAGE
    fi

    #
    # Remove circular link.
    #
    echo "SCRIPT: Remove circular link in /lib/modules"

    rm /mnt/lib/modules/`uname -r`/default 2>/dev/null 1>&2


    if [ "$PACKAGE" = foslight ]
    then
	echo "SCRIPT: DISABLE POST ..."

	# only disable POST on the first partition
	if [ ${partition} -eq 1 ]
	then
		do_command FALSE touch /mnt/var/diagd.skippost 2>/dev/null
		do_command FALSE rm -f /mnt/etc/config/fabos  2>/dev/null
		do_command FALSE echo "off" > /mnt/etc/config/fabos
	fi

    fi

    if [ "$PACKAGE" = factory -o "$PACKAGE" = dvt ]
    then
	echo "SCRIPT: Fixing up /etc/config entries..."

	# only turn off fabos on the first partition
	# This allows manufacturing process to use fruinit on clean install
	# and having the second partition on allows for badrootdev support
	# during power cycle tests.
	if [ ${partition} -eq 1 ]
	then
	    do_command FALSE rm -f /mnt/etc/config/fabos  2>/dev/null
	    do_command FALSE echo "off" > /mnt/etc/config/fabos
	    do_command FALSE rm -f /mnt/etc/config/foslight  2>/dev/null
	    do_command FALSE echo "on" > /mnt/etc/config/foslight
	    do_command FALSE rm -f /mnt/etc/config/chubby  2>/dev/null
	    do_command FALSE echo "off" > /mnt/etc/config/chubby
	fi
	# turn off the login timeout
	do_command FALSE cat > /mnt/etc/idle.conf << EOF
0
EOF
	do_command FALSE rm -f /mnt/etc/config/webtools 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/fwd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/evmd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/snmpd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/swdd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/wdtd 2>/dev/null

	do_command FALSE echo "off" > /mnt/etc/config/webtools
	do_command FALSE echo "off" > /mnt/etc/config/fwd
	do_command FALSE echo "off" > /mnt/etc/config/evmd
	do_command FALSE echo "off" > /mnt/etc/config/snmpd
	do_command FALSE echo "off" > /mnt/etc/config/swdd
	do_command FALSE echo "off" > /mnt/etc/config/wdtd

	do_command FALSE rm -f /mnt/etc/rc.d/rc.pwdinit 2>/dev/null

    fi

    if [  $major ]; then
        rm -f /mnt/dev/$node
    	mknod --mode=644 /mnt/dev/$node c $major 0
    fi
   
    ####################################
    # Copy kernel image to user flash only once
    #
    if [ ${partition} -eq 1 ]
    then

	mtds=`cat /proc/mtd | grep kernel | cut -f1 -d: | xargs echo`
	for mtd_dev in ${mtds} ; do
	    echo "SCRIPT: Writing Kernel to partition ${mtd_dev} of kernel flash"
	        do_command FALSE /sbin/flash_write \
			-i /mnt/boot/zImage.tree.initrd -o /dev/${mtd_dev}
	done

	mtds=`cat /proc/mtd | grep log | cut -f1 -d: | xargs echo`
	for mtd_dev in ${mtds} ; do
	    echo "SCRIPT: Clearing the partition ${mtd_dev} of kernel flash"
		cat /dev/zero > /dev/${mtd_dev} 2> /dev/null
	done

    fi

    echo "SCRIPT: Unmounting file system..."

    do_command FALSE umount ${TMPMNT}
  fi
done

####################################
# Update boot environment
#

#
# The new version of bootenv command checks the checksum 
# of bootenv partition. This doesn't work on platforms
# that don't support dual bootenv partitions and thus don't
# have partition checksum. So we run bootenv with -i 
# option to invalidate partition checksum first. This tell
# bootenv command to ignore checksum. 
#
bootenv  > /dev/null 2>&1
if [ $? -ne 0 ]
then
  bootenv -i
  do_command FALSE bootenv > /dev/null 2>&1
fi

echo "SCRIPT: Setting boot environment parameters..."
# remove the system test override variable
# NOTE do not use do_command on this because the variable may not exist,
# and the command will return a fail status, but this is not an indication
# of a failing install
bootenv -u NoSysTest 2> /dev/null

# The special characters in this bootenv variable value prevent the use of 
# do_command. So I have copied the content of do_command here.
bootenv -u LoadIdentifier 2> /dev/null
bootenv -v LoadIdentifiers "Fabric Operating System;Fabric Operating System"

do_command FALSE bootenv -v OSLoader 'MEM()0xF0000000;MEM()0xF0800000'
do_command FALSE bootenv -v OSRootPartition "${DEVICE}1;${DEVICE}2"
do_command FALSE bootenv -v AutoLoad 'yes'
do_command FALSE bootenv -v InitTest 'MEM()'
do_command FALSE bootenv -v OSLoadOptions 'quiet'
do_command FALSE bootenv -v SkipWatchdog 'yes'
# NOTE do not use do_command on this because the variable may not exist,
# and the command will return a fail status, but this is not an indication
# of a failing install
bootenv -u BadRootDev 2> /dev/null
bootenv -u SoftUpgrade 2> /dev/null
bootenv -u Upgrade 2> /dev/null

####################################
# Output ending instructions
#
if [ -f $PLATFORM/ending_instructions ]
then
    cat $PLATFORM/ending_instructions
else
    echo ""
    echo "SCRIPT: No platform specific instructions found."
    echo "SCRIPT: You may now reboot the system."
    echo ""
    echo "SCRIPT: Be sure you have a console connection to the system before rebooting."
    echo ""
fi
####################################
# Output overall results
#
exit_out
